﻿using System;
using System.Net.Sockets;

namespace TinySocket
{
    public static class SocketExtensions
    {
        public static void CloseSocket(Socket socket)
        {
            try
            {
                socket.Shutdown(SocketShutdown.Both);
            }
            catch { }
            finally
            {
                socket.Close();
            }
        }

        public static int ReadSafely(Socket socket,byte[] buffer,int offset,int size)
        {
            try
            {
                return socket.Receive(buffer, offset, size, SocketFlags.None);
            }
            catch (ObjectDisposedException)
            {
                return 0;
            }
        }

        public static bool ReadExactly(Socket socket,byte[] buffer,int offset,int count)
        {
            int bytesTransferred = 0;
            while (bytesTransferred < count)
            {
                int result = ReadSafely(socket, buffer, offset + bytesTransferred, count - bytesTransferred);
                if (result == 0)
                    return false;
                bytesTransferred = bytesTransferred + result;
            }
            return true;
        }

        public static Socket CreateTcpSocket()
        {
            return new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        }
    }
}